﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Jugg.Core.MediaItem
{
    public class MediaItemStorage : IMediaItemStorage
    {

        /// <summary>
        /// 文件存储,返回路径的相对路径
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="virtualPath">虚拟相对目录 /xxxx/xxx</param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public string Storage(MemoryStream stream, string virtualPath, string fileName)
        {
            string psth = virtualPath.TrimStart('~');
            virtualPath = "~" + psth;
            var physicalPath = WebHelper.mapPath(virtualPath);

            if (String.IsNullOrEmpty(physicalPath))
                throw new NoNullAllowedException("虚拟路径转换错误");
            if (!Directory.Exists(physicalPath))
                Directory.CreateDirectory(physicalPath);

            var fullPath = Path.Combine(physicalPath, fileName);
            using (var outStream = File.OpenWrite(fullPath))
            {
                stream.WriteTo(outStream);
                outStream.Flush();
                outStream.Close();
            }
            return psth.TrimEnd('/') + "/" + fileName;
        }
    }
}
